<template>
    <div class="file-upload-container">
      <el-upload
        class="file-uploader"
        drag
        :action="fullUploadUrl"
        :headers="computedHeaders"
        :data="extraData"
        :multiple="multiple"
        :show-file-list="true"
        :limit="limit"
        :on-success="handleSuccess"
        :on-error="handleError"
        :on-preview="handleDownload" 
        :on-remove="handleRemove"
        :before-upload="beforeUpload"
        v-model:file-list="fileList"
      >
        <div class="upload-area">
          <el-icon class="upload-icon"><UploadFilled /></el-icon>
          <p class="upload-title">拖拽文件到此处或<em>点击上传</em></p>
          <p class="upload-hint">最大50MB</p>
        </div>
      </el-upload>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import { UploadFilled } from '@element-plus/icons-vue'
  
  // Props
  const props = defineProps({
    headers: Object,
    extraData: Object,
    multiple: Boolean,
    limit: { type: Number, default: 5 },
    modelValue: { type: [Array, String], default: () => [] },
  })
  
  // Emits
  const emit = defineEmits(['update:modelValue', 'success'])
  
  // 文件列表
  interface FileItem {
    uid?: string
    name: string
    url: string
    size?: number
    status: string
    response?: any
  }
  
  const fileList = ref<FileItem[]>([])
  
  // 点击文件直接下载
  const handleDownload = (file: any) => {
    const url = file.url || file.response?.data?.url
    if (url) {
      const link = document.createElement('a')
      link.href = url
      link.download = file.name
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    } else {
      ElMessage.error('无法获取文件下载地址')
    }
  }
  
  // 上传地址
  const fullUploadUrl = computed(() => {
    const base = import.meta.env.VITE_API_BASE_URL || ''
    return `${base}/common/upload`
  })
  
  // headers
  const computedHeaders = computed(() => ({
    ...props.headers,
    Authorization: `Bearer ${localStorage.getItem('token') || ''}`
  }))
  
  // 同步父组件传入的 modelValue
  watch(() => props.modelValue, (val) => {
    const urls = Array.isArray(val) ? val : (val ? [val] : [])
    fileList.value = urls.map((url: unknown) => ({
      name: String(url).split('/').pop() || '',
      url: String(url),
      status: 'done'
    }))
  }, { immediate: true })
  
  // 上传前校验
  const beforeUpload = (file: File) => {
    const maxSize = 50 * 1024 * 1024
    if (file.size > maxSize) {
      ElMessage.error('文件不能超过 50MB')
      return false
    }
    return true
  }
  
  // 上传成功
  const handleSuccess = (response: any, file: any) => {
    ElMessage.success('上传成功')
    emit('success', response)
  
    const target = fileList.value.find(f => f.uid === file.uid)
    if (target) {
      target.response = response
      target.url = response.data?.url || target.url
      if (file.size) {
        target.size = file.size
      }
    }
  
    updateModelValue()
  }
  
  // 上传失败
  const handleError = (err: any) => {
    ElMessage.error('上传失败')
    console.error(err)
  }
  
  // 删除文件
  const handleRemove = (file: any) => {
    fileList.value = fileList.value.filter(f => f.uid !== file.uid)
    updateModelValue()
  }
  
  // 更新父组件 v-model
  const updateModelValue = () => {
    const urls = fileList.value.map(f => f.response?.data?.url || f.url)
    if (props.multiple) {
      emit('update:modelValue', urls)
    } else {
      emit('update:modelValue', urls[0] || '')
    }
  }
  </script>
  
  <style scoped lang="less">
  .file-upload-container {
    width: 100%;
    max-width: 800px;
    
    :deep(.el-upload) {
      width: 100%;
    }
    
    :deep(.el-upload-dragger) {
      padding: 40px 20px;
      border-radius: 8px;
      background-color: #f8fafc;
      border: 2px dashed #cbd5e1;
      transition: all 0.3s ease;
      
      &:hover {
        border-color: #6366f1;
        background-color: #f1f5f9;
      }
    }
    
    .upload-area {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      
      .upload-icon {
        font-size: 48px;
        color: #6366f1;
        margin-bottom: 16px;
      }
      
      .upload-title {
        margin: 0;
        font-size: 16px;
        color: #334155;
        
        em {
          font-style: normal;
          color: #6366f1;
          font-weight: 500;
        }
      }
      
      .upload-hint {
        margin: 8px 0 0;
        font-size: 14px;
        color: #94a3b8;
      }
    }
    
    :deep(.el-upload-list) {
      margin-top: 20px;
      
      .el-upload-list__item {
        padding: 12px;
        border-radius: 8px;
        transition: all 0.2s;
        border: 1px solid #e2e8f0;
        cursor: pointer;
        
        &:hover {
          background-color: #f8fafc;
          box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
        }
        
        .el-icon {
          color: #6366f1;
        }
      }
    }
  }
  </style>